<?php

namespace app\admin\service;

use app\admin\model\FileUpload;
use common\override\Storage;
use Tinywan\ExceptionHandler\Exception\BadRequestHttpException;
use Tinywan\ExceptionHandler\Exception\NotFoundHttpException;
use common\enum\ResultCode;
use Webman\Http\UploadFile;
use Illuminate\Database\QueryException;

class FileUploadService extends BaseCurdService
{
    /**
     * 获取文件列表
     * @param array $params 查询参数
     * @return array
     */
    public function getList(array $params): array
    {
        $query = FileUpload::query();
        return $this->paginateQuery($query, $params, ['name', 'original_name'], ['status']);
    }

    /**
     * 获取文件详情
     * @param int $id 文件ID
     * @return FileUpload|null
     */
    public function getInfo(int $id): ?FileUpload
    {
        $file = FileUpload::find($id);
        if (!$file) {
            throw new NotFoundHttpException(ResultCode::DATA_NOT_FOUND->getDescription());
        }
        return $file;
    }

    /**
     * 创建文件记录
     * @param array $data 文件数据
     * @return FileUpload
     */
    public function create(array $data): FileUpload
    {
        try {
            return FileUpload::create($data);
        } catch (QueryException $e) {
            // 检查是否是唯一索引冲突
            if (str_contains($e->getMessage(), 'uk_unique_id')) {
                // 如果是unique_id唯一索引冲突，查询并返回已存在的记录
                if (!empty($data['unique_id'])) {
                    $existingFile = FileUpload::where('unique_id', $data['unique_id'])->first();
                    if ($existingFile) {
                        return $existingFile;
                    }
                }
            }
            // 如果不是unique_id冲突或其他原因，重新抛出异常
            throw $e;
        }
    }

    /**
     * 删除文件记录
     * @param int $id 文件ID
     * @return bool|null
     */
    public function delete(int $id): ?bool
    {
        $file = FileUpload::find($id);
        if (!$file) {
            throw new NotFoundHttpException(ResultCode::DATA_NOT_FOUND->getDescription());
        }
        return $file->delete();
    }

    /**
     * 批量删除文件记录
     * @param array $ids 文件ID数组
     * @return int
     */
    public function batchDelete(array $ids): int
    {
        return FileUpload::whereIn('id', $ids)->delete();
    }

    /**
     * 上传文件
     * @param UploadFile $file 上传的文件
     * @return FileUpload
     */
    public function upload(UploadFile $file): FileUpload
    {
        try {
            [$result] = Storage::uploadFile([$file]);
            $existingFile = FileUpload::where('unique_id', $result['unique_id'])->first();
            if ($existingFile) {
                return $existingFile;
            }
            $data = [
                'name' => $result['save_name'],
                'original_name' => $result['origin_name'],
                'path' => $result['save_path'],
                'url' => $result['url'],
                'extension' => $result['extension'],
                'mime_type' => $result['mime_type'],
                'size' => $result['size'],
                'unique_id' => $result['unique_id'],
            ];
            return $this->create($data);
        } catch (\Exception $e) {
            throw new BadRequestHttpException('文件上传失败：' . $e->getMessage());
        }
    }
}